import { View } from '@tarojs/components'
import './index.scss'
import { useRef, useState } from 'react'

export function createUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

interface Circle {
  clientX: number,
  clientY: number,
  key: string
}


// 初始化
// 更新
function Bubble() {
  //数据驱动 UI，改变数据聚会重新渲染
  const [circles, setCircle] = useState<Circle[]>([])
  //改变数据不会重新渲染
  const timer = useRef<any>(null)

  function clickHandler(e) {
    const key = createUUID()
    let point = {...e.touches[0], key}
    circles.push(point)
    setCircle([...circles])
    //清除定时器
    clearTimeout(timer.current)
  }
  
  // 语义化
  function animationendhandler(key: string) {
    //定时器，动画结束后0.5s 执行这个函数
    timer.current = setTimeout(() => {
      //等动画结束运行函数删除所有创造的圆
      setCircle([])
    }, 500)
    // const data = circles.filter((point) => point.key != key)
    // setCircle(data)
  }


  return (
    <View className='index' onTouchStart={clickHandler}>
      {
        circles.map((circle) => (
          <View
            className='circle'
            key={circle.key}
            style={{left: circle.clientX - 50 + 'px' , top: circle.clientY - 50 + 'px'}}
            onAnimationEnd={() => animationendhandler(circle.key)}
          ></View>
        ))
      }
    </View>
  )
}

export default Bubble
